<?php
/**
 * Created by PhpStorm.
 * User: UEWARE
 * Date: 2019-7-18
 * Time: 12:34:37
 */
namespace App\Http\Controllers\WeChat\Diary\V1\User;

use App\Factory\MiniProgram;
use App\Http\Controllers\WeChat\WeChatController;
use App\Models\UserModel;
use Illuminate\Http\Request;

class AuthController extends WeChatController
{
    /**
     * 授权
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     */
    public function index(Request $request)
    {
        $data = $request->input();

        $encryptedData = $data['encryptedData'];
        $iv = $data['iv'];

        $user = MiniProgram::app()->encryptor->decryptData($this->sessionKey, $iv, $encryptedData);

        $userData['nickname'] = $user['nickName'];
        $userData['sex'] = $user['gender'];
        $userData['language'] = $user['language'];
        $userData['city'] = $user['city'];
        $userData['province'] = $user['province'];
        $userData['country'] = $user['country'];
        $userData['headimgurl'] = $user['avatarUrl'];
        $userData['is_auth'] = UserModel::IS_AUTH;

        try {
            UserModel::query()->where('id', $this->userId)->update($userData);
        } catch (\Exception $e) {
            return error(100000);
        }

        return success();
    }
}
